from goods.models import GoodsChannel
from goods.models import GoodsCategory, SKU


# 封装商品分类
def get_categories():
    # 1. 查询商品频道和分类
    categories = {}
    # 2.查询数据
    channels = GoodsChannel.objects.order_by('group', 'sequence')
    for channel in channels:
        # 取出组的编号
        group_id = channel.group_id

        # 3.添加一级分类到channels
        if group_id not in categories:
            categories[group_id] = {"channels": [], "sub_cats": []}
        cat1 = {"id": channel.category.id, "name": channel.category.name, "url": channel.url}
        categories[group_id]['channels'].append(cat1)

        # 4.添加二级分类,三级分类页面外键反向查找渲染
        for cat2 in channel.category.subs.all():
            categories[group_id]['sub_cats'].append(cat2)
    return categories


# 面包屑导航
def get_crumbs(sku_id):
    sku = SKU.objects.get(id=sku_id)
    return GoodsCategory.objects.get(id=sku.category_id)
